﻿using AutoMapper;
using BackData;
using Domain;
using Infratructure;
using MediatR;
using Newtonsoft.Json.Linq;
using Rabbit.API.Application.Command.Kill;
using Rabbit.API.DTOs;

namespace Rabbit.API.Application.Handler.Kill
{
    public class KillGetHandler:IRequestHandler<KillGetCommand,APIResult<KillDTO>>
    {
        private readonly IRepository<KillModel> killway;
        private readonly IMapper mapper;
        private readonly ILogger<KillGetHandler> log;

        public KillGetHandler(IRepository<KillModel> killway,IMapper mapper,ILogger<KillGetHandler> log) 
        {
            this.killway = killway;
            this.mapper = mapper;
            this.log = log;
        }
        /// <summary>
        /// 获取屠宰详情
        /// </summary>
        /// <param name="request">参数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>屠宰详情</returns>
        public Task<APIResult<KillDTO>> Handle(KillGetCommand request, CancellationToken cancellationToken)
        {
            APIResult<KillDTO> res = new APIResult<KillDTO>();
            try
            {
                var kill = killway.GetAll().FirstOrDefault(x => x.IsDel == false&&x.Id==request.KillId);
                var result = mapper.Map<KillDTO>(kill);
                if (result != null)
                {
                    log.LogInformation($"获取屠宰详情成功");
                    res.Message = "获取屠宰详情成功";
                    res.Num = StateCode.OK;
                    res.Data = result;
                }
                else
                {
                    log.LogInformation($"获取屠宰详情失败");
                    res.Message = "获取屠宰详情失败";
                    res.Num = StateCode.Fail;
                }

                return Task.FromResult(res);
            }
            catch (Exception ex)
            {
                log.LogError($"获取屠宰详情发生异常{ex.Message}");
                throw;
            }
        }
    }
}
